package com.xjd.transport.work;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.xjd.transport.impl.FutureImpl;

public class SendWork extends Work {

	InputStream src;
	OutputStream dest;
	byte[] buf;

	public SendWork(InputStream src, OutputStream dest, byte[] buf, FutureImpl future) {
		super(future);
		this.src = src;
		this.dest = dest;
		this.buf = buf;
	}

	@Override
	public void doWork() {
		try {
			long totall = 0;
			int count = 0;
			while (!cancelling && (count = src.read(buf)) != -1) {
				if (count > 0) {
					dest.write(buf, 0, count);
					totall += count;
					synchronized (future.getDoneBytesLock()) {
						future.setDoneBytes(totall);
					}
				}
			}
			synchronized (future.getStateLock()) {
				future.setState(STATE_STOPED);
				if (count == -1) {
					future.setFinishState(FINISH_STATE_SUCCESS);
				} else {
					future.setFinishState(FINISH_STATE_CACELLED);
				}
				future.getStateLock().notifyAll();
			}
		} catch (IOException e) {
			synchronized (future.getStateLock()) {
				future.setState(STATE_STOPED);
				future.setFinishState(FINISH_STATE_FAILED);
				future.setCause(e);
				future.getStateLock().notifyAll();
			}
		}
		
		future.fireFutureListener();

		try {
			src.close();
		} catch (IOException e) {
			// DoNothing
		}
	}

}
